package com.marketlive.app.b2c.account;

import com.marketlive.app.b2c.WebUtil;
import com.marketlive.app.b2c.common.constants.ActionForwards;

/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

import com.marketlive.app.b2c.common.constants.RequestParams;
import com.marketlive.app.b2c.common.constants.Errors;
import com.marketlive.app.b2c.common.constants.ConfigProperties;
import com.marketlive.app.b2c.session.StackBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.marketlive.biz.session.context.ICommerceSession;
import org.marketlive.entity.account.ICustomer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;
import java.util.Stack;


/**
 * Login action for My Account.  Either a shopper logs in as a returning customer or
 * if s/he is not already registered in the system then s/he can register.
 * For details about parameters of methods please see the package description.
 */
public class LoginAction extends AbstractAccountAction {

	private static Log log = LogFactory.getLog(LoginAction.class);

	/** Value of the request parameter identifying Account pages. */
	private static final String ACCOUNT_PAGE = "account";
	/** Constant identifying current page as Login page in the AccountRegisterForm. */
	private static final String LOGIN_PAGE = "login";
	/** Constant for Loin in image text. */
	public static final String LOGIN_IMAGE_ALT_TEXT = "img.altTxt.myAccountRegisterLogin";


	/**
	 * Executes default method (view) if method parameter is not specified.
	 *
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	protected ActionForward unspecified(ActionMapping mapping,
										ActionForm form,
										HttpServletRequest request,
										HttpServletResponse response) throws Exception {
		return view(mapping, form, request, response);
	}

	/**
	 * Prepare the page for display.
	 * For details about parameters of method please see the package description.
	 */
	public ActionForward view(ActionMapping mapping,
							  ActionForm form,
							  HttpServletRequest request,
							  HttpServletResponse response)
			throws Exception {

		// set up header nav
		AccountRegisterForm accountRegisterForm = AccountDispatcherAction.getAccountRegisterForm(request);
		setupHeaderNav(accountRegisterForm);

		return super.view(mapping, form, request, response);
	}

	/**
	 * Take shopper to register user page.
	 * For details about parameters of method please see the package description.
	 */
	public ActionForward register(ActionMapping mapping,
								  ActionForm form,
								  HttpServletRequest request,
								  HttpServletResponse response)
			throws Exception {

		log.debug("LoginAction register()");

		ActionForward nextAction = WebUtil.findForward(request, mapping, ActionForwards.SUCCESS_KEY);
		ICommerceSession commerceSession = WebUtil.getCommerceSession(request);
        String whence = null;
        AccountRegisterForm accountRegisterForm = AccountDispatcherAction.getAccountRegisterForm(request);

		try {
			commerceSession.loginGuest();
			whence = request.getParameter(RequestParams.FROM);
			if (null != whence) {
				accountRegisterForm.setWhence(whence);
			}
			nextAction = WebUtil.findForward(request, mapping, ActionForwards.REGISTER_KEY);
		} catch (Exception e) {
			log.debug("Exception is: " + e.getMessage());
		}
		return nextAction;
	}

	/**
	 * Login returning customer.
	 * For details about parameters of method please see the package description.
	 */
	public ActionForward submit(ActionMapping mapping,
								ActionForm form,
								HttpServletRequest request,
								HttpServletResponse response)
			throws Exception {

		log.debug("LoginAction submit()");
		String userEmail = null;
		String userPassword = null;
		AccountRegisterForm accountRegisterForm = (AccountRegisterForm) form;
		ICommerceSession commerceSession = WebUtil.getCommerceSession(request);
		ActionForward nextAction = WebUtil.findForward(request, mapping, ActionForwards.SUCCESS_KEY);

		try {
			userEmail = accountRegisterForm.getLoginEmail();
			userPassword = accountRegisterForm.getLoginPassword();
			boolean isSuccessfullyLoggedIn = commerceSession.login(userEmail, userPassword);
			if (isSuccessfullyLoggedIn == true) {
				ICustomer customer = commerceSession.getCustomer();
				accountRegisterForm.setDoneWithRegistration(true);
				Set addr = customer.getContactsInAddressBook();
				if (addr.isEmpty()) {
					accountRegisterForm.setAddressListShown(false);
				} else {
					accountRegisterForm.setAddressListShown(true);
				}

				request.setAttribute(RequestParams.HREF_REQUEST_PARAM_NAME, ACCOUNT_PAGE);

				// check to see if the user was sent to this page by interstitial login
				StackBean stackBean = (StackBean) request.getSession(false).getAttribute(RequestParams.INTERSTITIAL_LOGIN);
				if (stackBean != null) {
					Stack destination = stackBean.getDestination();
					if ((destination != null) && (!destination.isEmpty())) {
						nextAction = (ActionForward) destination.pop();
					} else {
						nextAction = WebUtil.findForward(request, mapping, ActionForwards.GATEWAY_KEY);
					}
				} else {
					// go to configured success path
					nextAction = WebUtil.findForward(request, mapping, ActionForwards.GATEWAY_KEY);
				}

				// clear the password entered by the shopper in the login form.
				accountRegisterForm.setLoginPassword(null);

			} else {
				postGlobalError(Errors.LOGIN_INVALID, Errors.LOGIN_INVALID_PSW_RECOVERY_LINK, request);
				nextAction = WebUtil.findForward(request, mapping, ActionForwards.TRYAGAIN_KEY);
			}

		} catch (Exception e) {
			log.debug("Exception is: " + e.getMessage());
		}

		return nextAction;
	}

	/**
	 * Utility method to setup the header navigation strings in Login.jsp.
	 *
	 * @param accountRegisterForm The form used throughout My Account pages which holds header navigation fields.
	 */
	protected void setupHeaderNav(AccountRegisterForm accountRegisterForm) {
		accountRegisterForm.setNavigationImage(ConfigProperties.LOGIN_IMAGE);
		accountRegisterForm.setNavigationMsg(LOGIN_IMAGE_ALT_TEXT);
		accountRegisterForm.setRequiredMsgShown(false);
		accountRegisterForm.setShowNavigation(false);
		accountRegisterForm.setCurrentPage(LOGIN_PAGE);
	}

	/**
	 * Validate the login form.
	 * The validation to perform depends on whether login or register was selected.
	 * For details about parameters of method please see the package description.
	 */
	public ActionMessages validate(ActionMapping mapping, ActionForm form,
								 HttpServletRequest request) {

		log.debug("validate() start");
		try {
			String method = super.getMethodName(mapping, form, request, null, RequestParams.METHOD);
			if ((method != null) && (RequestParams.METHOD_SUBMIT.equals(method))) {
				return super.validate(mapping, form, request, mapping.getPath());
			} else {
				// Either it's not a login or the shopper selected register so bypass validation.
				return null;
			}
		} catch (Exception e) {
			log.debug("Exception: " + e);
			return null;
		}
	}

}
